package com.yunfinal.api.service;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.config.*;
import com.jfinal.core.FastControllerFactory;
import com.jfinal.core.paragetter.ParaProcessorBuilder;
import com.jfinal.json.MixedJsonFactory;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.server.undertow.PropExt;
import com.jfinal.server.undertow.UndertowServer;
import com.jfinal.template.Engine;

public class JFinalApiConfig extends JFinalConfig {
    public static void main(String[] args) {
        start(JFinalApiConfig.class);
    }

    /**
     * 供参考，如有特殊定制要求，复制本方法的代码新建自己的Config类，进行启动就OK
     *
     * @param jFinalConfigClass
     */
    public static void start(Class<? extends JFinalConfig> jFinalConfigClass) {
        System.out.println(jFinalConfigClass);
        PropExt prop = new PropExt("undertow.txt");
        UndertowServer.create(jFinalConfigClass)
                .configWeb(
                        builder -> {
                            // 配置 WebSocket，ApiReportSocket接口报告
                            String webSocketEndpointClass = "com.yunfinal.api.service.doc.ApiReportSocket";
                            if (prop.getBoolean(webSocketEndpointClass, false)) {
                                builder.addWebSocketEndpoint(webSocketEndpointClass);
                            }
                        })
                .start();
    }

    @Override
    public void configConstant(Constants me) {
        Prop p = getProp();
        me.setDevMode(p.getBoolean("devMode", false));
        me.setReportAfterInvocation(false);
        //JFinalJson 与 FastJson 混合做 json 转换
        me.setJsonFactory(new MixedJsonFactory());
        //控制器缓存池
        me.setControllerFactory(new FastControllerFactory());
        //控制器JSON参数构建器
        ParaProcessorBuilder.me.regist(JSONObject.class, ApiJsonGetter.class, "{}");
    }

    public static Prop getProp() {
        try {
            return PropKit.getProp();
        } catch (Exception e) {
            return PropKit.use("JFinalApiConfig.txt");
        }
    }

    @Override
    public void configEngine(Engine me) {
        me.setBaseTemplatePath("webapp").setToClassPathSourceFactory();
    }
    @Override
    public void configRoute(Routes me) {}
    @Override
    public void configPlugin(Plugins me) {}
    @Override
    public void configInterceptor(Interceptors me) {}
    @Override
    public void configHandler(Handlers me) {}
}
